package com.lvhh.pay;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class utils {
    public static String creatStringA(SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        //System.out.println("字符串:"+sb.toString());
        sbkey = sbkey.append("key=" + key);
//        //MD5加密,结果转换为大写字符
//        String sign = null;
//        try {
//            sign = DigestUtils.md5DigestAsHex(sbkey.toString().getBytes("utf-8")).toUpperCase();
//        } catch (UnsupportedEncodingException e) {
//            // TODO 自动生成的 catch 块
//            e.printStackTrace();
//        }
//        System.out.println("MD5加密值:" + sign);
//        //MD5Util.MD5Encode();
//// return sb.toString()+"sign="+sign;
        return sbkey.toString();
    }

    public static String createSign(String stringA) {

        return MD5(stringA).toUpperCase();
    }

    public static String MD5(String str) {

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes("utf-8"));
            byte[] encrypt = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : encrypt) {
                String s = Integer.toHexString(b & 0xFF);
                if (str.length() == 1) {
                    s = "0" + s;
                }
                sb.append(s);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
     return null;
    }

    public static void main(String[] args) {

    }
}
